package com.ruoyi.framework.security.handle;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WxUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.security.wx.WxAuthenticationToken;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;

@Component("wxAuthenticationProvider")
public class WxAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IWxUserService wxUserService;

    /**
     * 根据openId获取到wxUser，生成token
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String openId = (String) authentication.getCredentials();

        //根据openId查询wxUser
        WxUser wxUser = wxUserService.selectWxUserByOpenId(openId);
        if( wxUser == null ){
            //无wxuser数据，则生成
            WxUser wu = new WxUser();
            wu.setId(IdUtils.fastSimpleUUID());
            wu.setOpenId(openId);
            wu.setStatus(UserConstants.EXCEPTION);  //默认为非正常状态
            wu.setCreateTime(DateUtils.getNowDate());
            wxUserService.insertWxUserNoToken(wu);
            wxUser = wu;
        }

        SysUser sysUser = new SysUser();
        //获取到wxUser数据，填充到loginUser上，
        sysUser.setNickName(wxUser.getNickName());
        sysUser.setUserName(wxUser.getNickName());
        sysUser.setAvatar(wxUser.getAvatarUrl());
        if(wxUser.getUserId() != null){
            sysUser = sysUserService.selectUserById(wxUser.getUserId());
        }


        LoginUser loginUser = new LoginUser(wxUser, new HashSet<>(1));
        loginUser.setUser(sysUser);

        Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();
        // 构建返回的用户登录成功的token
        return new WxAuthenticationToken(loginUser, null, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (WxAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
